<?php
// $Id$

/**
 * Controller_News 控制器
 */
class Controller_News extends Controller_Abstract
{
	function __construct($app){
		parent::__construct($app);
		$newstype = new Newstype();
		$arr_newstype = $newstype->get_select_list(0,'',array(1,4,5,6));
		unset($arr_newstype[0]);
		unset($arr_newstype[1]);
		$this->_view['newstype'] = $arr_newstype;
	}
	function actionIndex()
	{
        // 为 $this->_view 指定的值将会传递数据到视图中
		# $this->_view['text'] = 'Hello!';
		
		$flag = Q::ini('appini/flag');
		$this->_view['flag'] = $flag;
		$page = (int)$this->_context->page;
		if ($page==0) $page++;
		//echo $page;exit;
		$limit = $this->_context->limit ? $this->_context->limit : 15;
		
		//搜索
		$search_where = "";
		$search_list_temp = array('isdelete=0');
		$title = '';
		$type_id = 0;
		$home_flag = '';
		$top_flag = '';
		if (isset($_GET['title'])){
			$title = addslashes(trim($_GET['title']));
			$type_id = $_GET['type_id'];
			$home_flag = $_GET['home_flag'];
			$top_flag = $_GET['top_flag'];
			$search_list = array();			
			if (strlen($title)) {
				array_push($search_list_temp," title like '%$title%'");
			}
			if ($type_id) {
				$newstype = new Newstype();
				$arr_temp = $newstype->get_ids($type_id);
				if($arr_temp){
					$arr_str = implode(',',$arr_temp);
					array_push($search_list_temp," type_id in ($arr_str)");
				}
			}
			if (strlen($home_flag)) {
				array_push($search_list_temp," home_flag=".$home_flag);
			}
			if (strlen($top_flag)) {
				array_push($search_list_temp," top_flag=".$top_flag);
			}			
		}
		$this->_view['title'] = stripslashes($title);
		$this->_view['type_id'] = $type_id;
		$this->_view['home_flag'] = $home_flag;
		$this->_view['top_flag'] = $top_flag;
		//得到该用户可操作的新闻类型
		$user = $this->_app->currentUser();
		$news_op = array();
		if(isset($user['news_op'])){
			if(!empty($user['news_op'])){
				$news_op = explode(',',$user['news_op']);
			    array_push($search_list_temp," type_id in (".$user['news_op'].")");	
			}
		}
		$this->_view['news_op'] = $news_op;
		//-----------------------------------------------
		$search_where = implode(' and ',$search_list_temp);
		
		$q = News::find($search_where)->order('id desc')->limitPage($page, $limit);
		$list = $q->getAll()->toArray();
		$this->_view['pager'] = $q->getPagination();
		$this->_view['list'] = $list;
		$this->_view['start'] = ($page-1)*$limit;
		$this->_view['subject'] = "信息管理";
	}
	function actionCreate(){
		//继续添加类型不用再选
		$create_type_id = 0;
		if(isset($_GET['create_type_id'])){
			$create_type_id = $_GET['create_type_id'];
		}
		//得到该用户可操作的新闻类型
		$user = $this->_app->currentUser();
		$news_op = array();
		if(isset($user['news_op'])){
			if(!empty($user['news_op'])){
				$news_op = explode(',',$user['news_op']);
			    //array_push($search_list_temp," type_id in (".$user['news_op'].")");	
			}
		}
		$this->_view['news_op'] = $news_op;
		//-----------------------------------------------
		$flag = Q::ini('appini/flag');
		$rootdir = dirname(dirname(dirname(dirname(__FILE__)))).DIRECTORY_SEPARATOR;
		$error_pic_msg = '';
		$alert = '';
		$this->_view['flag'] = $flag;
		$this->_view['subject'] = "信息管理";
		$this->_view['error_pic_msg'] = $error_pic_msg;		
		if ($this->_context->isPOST() && isset($_POST['title'])){
			@extract($_POST);
			$create_type_id = $type_id;			
			$title 	= addslashes(trim($title));
			$source = addslashes(trim($source));
			$author = addslashes(trim($author));
			$content= addslashes(trim($content));
			$now = strtotime($release_date);
			$user = $this->_app->currentUser();
			$form_value = array(
							'type_id'		=> $type_id,
							'title'			=> $title,
							'source'		=> $source,
							'author'		=> $author,
							'content'		=> $content,
							'release_date'	=> $now,
							'admin_id'		=> $user['id'],
							'recommend_flag'=> $recommend_flag,
							'top_flag'		=> $top_flag,
							'home_flag'		=> $home_flag,
							'keywords'      => $keywords,
							'description'   => $description,
							);
			$pic = '';
			$file_pic = $_FILES['pic'];
			if($file_pic['size']){
				$temp=$file_pic['tmp_name'];
				$filename = $file_pic["name"];	
				$filetype=substr(strrchr($filename,"."),1);	
				$filesize = $file_pic["size"];
				$filetype = strtolower($filetype);
				$refusetype = array("jpg","png","gif");
				if((!in_array($filetype,$refusetype) || ($filesize > 1024*1024))){
					if(!in_array($filetype,$refusetype)){
						$error_pic_msg = "请上传图片文件！";
					}
					if($filesize > 1024*1024){
						$error_pic_msg .= "文件超过1M，不允许上传！";
					}
					$this->_view['error_pic_msg'] = $error_pic_msg;
					return;
				}	
				$source = $temp;
				$desfilename = time().'.'.$filetype;
				$my_dir = 'upload_files'.DIRECTORY_SEPARATOR.'picture'.DIRECTORY_SEPARATOR;
				$date_dir = Helper_Util::mk_date_dir($rootdir.$my_dir);
				$pic = $my_dir.$date_dir.$desfilename;
				$destination = $rootdir.$pic;
				//echo $destination.'<br />';
				copy($source,$destination);
				$form_value['pic'] = $pic;
			}
			//print_r($form_value);
			$news = new News($form_value);
			$pid = $news->save()->id;
			if(isset($_FILES['fj'])){
				$fj = $_FILES['fj'];
				foreach($fj['size'] as $k => $v){
					if($v){
						$temp=$fj['tmp_name'][$k];
						$filename = $fj["name"][$k];	
						$filetype=substr(strrchr($filename,"."),1);	
						$filesize = $fj["size"][$k];
						$filetype = strtolower($filetype);
						$source = $temp;
						$desfilename = time().'_'.$k.'.'.$filetype;
						$my_dir = 'upload_files'.DIRECTORY_SEPARATOR.'enclosure'.DIRECTORY_SEPARATOR;
						$date_dir = Helper_Util::mk_date_dir($rootdir.$my_dir);
						$path = $my_dir.$date_dir.$desfilename;
						$destination = $rootdir.$path;
						copy($source,$destination);
						$form_value_en = array(
											'pid'	=> $pid,
											'name'	=> $fj['name'][$k],
											'path'	=> $path,
											);
						$enclosure = new Enclosure($form_value_en);
						$enclosure->save();
					}
				}
			}
			//推送至mynep
			Helper_Util::soap_addnews($news);

			$alert = "<script language='javascript'>if(confirm('新闻添加成功，是否继续添加？')){window.open('".url('news/create',array('create_type_id'=>$create_type_id))."','_self');}else{window.open('".url('news')."','_self');}</script>";
			
		}
		$this->_view['alert'] = $alert;
		$this->_view['create_type_id'] = $create_type_id;
		
	}
	function actionEdit(){
		//得到该用户可操作的新闻类型
		$user = $this->_app->currentUser();
		$news_op = array();
		if(isset($user['news_op'])){
			if(!empty($user['news_op'])){
				$news_op = explode(',',$user['news_op']);
			    //array_push($search_list_temp," type_id in (".$user['news_op'].")");	
			}
		}
		$this->_view['news_op'] = $news_op;
		//-----------------------------------------------
		$flag = Q::ini('appini/flag');
		$rootdir = dirname(dirname(dirname(dirname(__FILE__)))).DIRECTORY_SEPARATOR;
		$error_pic_msg = '';
		$alert = '';
		$this->_view['flag'] = $flag;
		
		$this->_view['rootdir'] = $rootdir;
		$this->_view['subject'] = "信息管理";
		
		$id = $this->_context->id;
		$news = News::find()->getById($id);	
		if ($this->_context->isPOST() && isset($_POST['title'])){
			@extract($_POST);						
			$title 	= addslashes(trim($title));
			$source = addslashes(trim($source));
			$author = addslashes(trim($author));
			$content= addslashes(trim($content));
			$now = strtotime($release_date);
			$user = $this->_app->currentUser();
			$form_value = array(
							'id'			=> $id,
							'type_id'		=> $type_id,
							'title'			=> $title,
							'source'		=> $source,
							'author'		=> $author,
							'content'		=> $content,
							'update_date'	=> $now,
							'release_date'	=> $now,
							'update_id'		=> $user['id'],
							'recommend_flag'=> $recommend_flag,
							'top_flag'		=> $top_flag,
							'home_flag'		=> $home_flag,
							'keywords'      => $keywords,
							'description'   => $description,
							);
			$pic = '';
			if(isset($_FILES['pic'])){
			$file_pic = $_FILES['pic'];
				if($file_pic['size']){
					$temp=$file_pic['tmp_name'];
					$filename = $file_pic["name"];	
					$filetype=substr(strrchr($filename,"."),1);	
					$filesize = $file_pic["size"];
					$filetype = strtolower($filetype);
					$refusetype = array("jpg","png","gif");
					if((!in_array($filetype,$refusetype) || ($filesize > 1024*1024))){
						if(!in_array($filetype,$refusetype)){
							$error_pic_msg = "请上传图片文件！";
						}
						if($filesize > 1024*1024){
							$error_pic_msg .= "文件超过1M，不允许上传！";
						}
						$this->_view['error_pic_msg'] = $error_pic_msg;
						return;
					}	
					$source = $temp;
					$desfilename = time().'.'.$filetype;
					$my_dir = 'upload_files'.DIRECTORY_SEPARATOR.'picture'.DIRECTORY_SEPARATOR;
					$date_dir = Helper_Util::mk_date_dir($rootdir.$my_dir);
					$pic = $my_dir.$date_dir.$desfilename;
					$destination = $rootdir.$pic;
					//echo $destination.'<br />';
					copy($source,$destination);
					$form_value['pic'] = $pic;
				}
			}
			//print_r($form_value);
			//$log_rec = Helper_Util::toArray($news);
			$news -> changeProps($form_value);
			$news -> save();
			//Log::addlog(1, 'News', $news->id(), $log_rec, '修改新闻：'.$news->title, NULL, 'news');
			if(isset($_FILES['fj'])){
				$fj = $_FILES['fj'];
				foreach($fj['size'] as $k => $v){
					if($v){
						$temp=$fj['tmp_name'][$k];
						$filename = $fj["name"][$k];	
						$filetype=substr(strrchr($filename,"."),1);	
						$filesize = $fj["size"][$k];
						$filetype = strtolower($filetype);
						$source = $temp;
						$desfilename = time().'_'.$k.'.'.$filetype;
						$my_dir = 'upload_files'.DIRECTORY_SEPARATOR.'enclosure'.DIRECTORY_SEPARATOR;
						$date_dir = Helper_Util::mk_date_dir($rootdir.$my_dir);
						$path = $my_dir.$date_dir.$desfilename;
						$destination = $rootdir.$path;
						copy($source,$destination);
						$form_value_en = array(
											'pid'	=> $id,
											'name'	=> $fj['name'][$k],
											'path'	=> $path,
											);
						$enclosure = new Enclosure($form_value_en);
						$enclosure->save();
					}
				}
			}
			$alert = "<script language='javascript'>if(confirm('该条信息修改成功，是否继续修改？')){window.open('".url('news/edit',array('id'=>$id))."','_self');}else{window.open('".url('news')."','_self');}</script>";
		}
	 	
	 	$myData = $news->toArray();
	 	if(isset($_GET['actionValue'])){
	 		$actionValue = $_GET['actionValue'];
	 		if($actionValue == 'deletePic'){
	 			if(is_file($rootdir.$myData['pic'])){
	 				unlink($rootdir.$myData['pic']);
	 				$myData['pic'] = '';
	 				$form_value_pic = array(
							'id'			=> $id,
							'pic'			=> '',
							);
					$news -> changeProps($form_value_pic);
					$news -> save();
	 				$alert = "<script language='javascript'>alert('图片已经删除！');</script>";
	 			}
	 		}
	 		if($actionValue == 'deleteEnc'){
	 			$en_id = $_GET['en_id'];
	 			//echo $en_id;
	 			$enc = Enclosure::find()->getById($en_id);
	 			$enclosure = $enc->toArray();
	 			//echo $enclosure;
	 			if(is_file($rootdir.$enclosure['path'])){
	 				unlink($rootdir.$enclosure['path']);
	 				Enclosure::meta()->destroyWhere('id = ?',$en_id);
	 				$alert = "<script language='javascript'>alert('附件已经删除！');</script>";
	 			}
	 		}
	 	}
	 	$enclosureData = Enclosure::find('pid='.$id)->getAll()->toArray();
	 	$this->_view['enclosureData'] = $enclosureData;
	 	$this->_view['myData'] = $myData;
		
		$this->_view['error_pic_msg'] = $error_pic_msg;	
		
		
		$this->_view['alert'] = $alert;
	}
	function actionDelete(){
		// destroyWhere() 方法的参数和 find() 方法完全一致
		$news = News::find('id = ?', $this->_context->id)->query();
		//$log_rec = Helper_Util::toArray($news);
	 	$news->isdelete = 1;
	 	$news->save();
		//Log::addlog(2, 'News', $news->id(), $log_rec, '删除新闻：'.$news->title, NULL, 'news ');
		return $this->_redirect(url(''));
	}
	
}


